<template>
  <div class="address-container">
    <LayoutHeaderTitle title="我的地址" />
    <div class="no-list" v-if="list.length === 0">
      <nuxt-link :to="{ name: 'user-addAddress' }">
        你还没有添加地址~去添加!
      </nuxt-link>
    </div>
    <template v-else>
      <van-address-list
        v-model="chooseId"
        :list="list"
        default-tag-text="默认"
        @edit="onEdit"
        @add="$router.push({ name: 'user-addAddress' })"
      />
      <div class="del">
        <van-button
          @click="isShowDelModal = true"
          type="warning"
          :disabled="!chooseId"
          block
          round
        >
          删除
        </van-button>
      </div>
    </template>
    <ModalConfirm
      title="删除地址"
      :desc="delDesc"
      v-model="isShowDelModal"
      @submit="goDel"
    />
  </div>
</template>

<script>
export default {
  middleware: "authenticated",
  layout: "notabbar",
  async asyncData({ app }) {
    let list = [];
    try {
      const { data, status } = await app.$apiGetAddress();
      if (status === 0) list = data;
    } catch (error) {
      console.log(error);
    }
    return { list };
  },
  data: () => ({
    chooseId: null,
    list: [],
    isShowDelModal: false
  }),
  methods: {
    onEdit(a) {
      this.$router.push({
        name: "user-editAddress",
        params: { address_id: a.id }
      });
    },
    getAddress(loading) {
      const loadInstance = loading || this.$helperLoadding("");
      this.$apiGetAddress()
        .then(res => {
          const { data, status } = res;
          if (status === 0) {
            this.list = data;
          }
        })
        .finally(() => {
          loadInstance.clear();
        });
    },
    goDel() {
      if (!this.chooseId) {
        return;
      }
      const load = this.$helperLoadding("");
      this.$apiDelAddress({
        address_id: this.chooseId
      }).finally(() => {
        this.chooseId = null;
        this.getAddress(load);
        this.isShowDelModal = false;
      });
    }
  },
  computed: {
    delDesc() {
      if (!this.chooseId) {
        return "删除选中的地址之后无法恢复，是否删除？";
      }
      let info = this.list.find(i => i.id === this.chooseId);
      return `<span class='red padding'>${info.name} ${info.tel} ${info.address} </span>删除后无法恢复，是否删除？`;
    }
  }
};
</script>

<style lang="scss" scoped>
.address-container {
  padding: 50px 0;
  position: relative;
  font-size: 14px;
  ::v-deep .van-address-list {
    padding-bottom: 20px;
  }
  ::v-deep .van-address-item__edit {
    position: absolute;
    font-size: 16px;
  }
  .add {
    text-align: center;
  }
  .del {
    padding: 20px;
  }
  .no-list {
    padding-top: 30px;
    text-align: center;
  }
}
</style>
